<template>
  <div class="discover-content-container">    
    <div class="category-content-container">
      <div class="discover-items">
        <div v-if="notes.length === 0" class="loading">加载中...</div>
        <div class="discover-item" v-for="note in notes" :key="note.note_id" @click="goToNoteDetail(note)">
          <div class="discover-image">
            <img v-if="note.media_type === 'image'" :src="note.media_url" :alt="note.title">
            <VideoPoster
              v-else-if="note.media_type === 'video'"
              :videoSrc="note.media_url"
              width="100%"
              height="100%"
              :canvasWidth="320"
              :canvasHeight="180"
              @click="goToNoteDetail(note)"
            />
            <div 
              v-if="note.type" 
              class="category-tag"
              :class="getCategoryTagClass(note.type)"
            >
              {{ note.type }}
            </div>
          </div>
          <div class="discover-title">{{note.title}}</div>
          <div class="discover-user">
            <div class="user-info">
              <img :src="note.avatar_url" class="small-avatar" alt="用户头像">
              <span>{{note.nickname}}</span>
            </div>
            <div class="publish-date">
              <svg class="calendar-icon" viewBox="0 0 24 24" fill="currentColor">
                <path d="M19,4H18V2H16V4H8V2H6V4H5C3.9,4 3,4.9 3,6V20C3,21.1 3.9,22 5,22H19C20.1,22 21,21.1 21,20V6C21,4.9 20.1,4 19,4M19,20H5V10H19V20M19,8H5V6H19V8Z"/>
              </svg>
              <span class="date">{{ formatDate(note.updated_at || note.create_time) }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';
import VideoPoster from '@/components/VideoPoster.vue';

export default {
  name: 'DiscoverContent',
  components: {
    VideoPoster
  },
  setup() {
    const router = useRouter();
    const notes = ref([]);
    
    // 格式化日期为YYYY-MM-DD格式
    const formatDate = (timestamp) => {
      if (!timestamp) return '未知日期';
      
      try {
        const date = new Date(timestamp);
        
        // 检查日期是否有效
        if (isNaN(date.getTime())) {
          return '未知日期';
        }
        
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        
        return `${year}-${month}-${day}`;
      } catch (error) {
        console.error('日期格式化错误:', error);
        return '未知日期';
      }
    };
    
    // 获取分类标签样式
    const getCategoryTagClass = (type) => {
      switch(type) {
        case 'live': return 'live-tag';
        case 'drama': return 'drama-tag';
        default: return '';
      }
    };
    
    // 跳转到笔记详情页
    const goToNoteDetail = (note) => {
      router.push({
        path: '/mecont',
        query: {
          userId: note.user_id,
          noteId: note.note_id
        }
      });
    };
    
    // 获取所有笔记数据
    const fetchAllNotes = async () => {
      try {
        console.log('获取所有笔记数据');
        const response = await axios.get('http://1.14.98.17:8765/api/notes');
        
        if (response.data.success) {
          // 1. 按updated_at排序（越近的排在前面）
          const sortedNotes = response.data.data.sort((a, b) => {
            const dateA = new Date(a.updated_at || a.create_time);
            const dateB = new Date(b.updated_at || b.create_time);
            return dateB - dateA; // 降序排列，最新的在前面
          });
          
          console.log('按时间排序后的笔记:', sortedNotes);
          
          // 2. 获取每个笔记的媒体和用户信息
          const notesWithDetails = await Promise.all(
            sortedNotes.map(async (note) => {
              try {
                // 获取笔记媒体
                const mediaResponse = await axios.get(`http://1.14.98.17:8765/api/notes/${note.note_id}/media`);
                let mediaUrl = '';
                let mediaType = 'image';
                
                if (mediaResponse.data.success && mediaResponse.data.data.length > 0) {
                  const firstMedia = mediaResponse.data.data[0];
                  mediaUrl = firstMedia.media_url;
                  mediaType = firstMedia.media_type;
                }
                
                // 获取用户信息
                const userResponse = await axios.get(`http://1.14.98.17:8765/api/users/${note.user_id}`);
                let nickname = '匿名用户';
                let avatarUrl = '';
                
                if (userResponse.data.success) {
                  nickname = userResponse.data.data.nickname || '匿名用户';
                  avatarUrl = userResponse.data.data.avatar_url || '';
                }
                
                // 返回完整的笔记信息
                return {
                  ...note,
                  media_url: mediaUrl,
                  media_type: mediaType,
                  nickname: nickname,
                  avatar_url: avatarUrl
                };
              } catch (error) {
                console.error(`获取笔记 ${note.note_id} 的详细信息失败:`, error);
                return note;
              }
            })
          );
          
          console.log('带详细信息的笔记:', notesWithDetails);
          notes.value = notesWithDetails;
        }
      } catch (error) {
        console.error('获取笔记数据失败:', error);
      }
    };
    
    onMounted(() => {
      fetchAllNotes();
    });

    return {
      notes,
      formatDate,
      getCategoryTagClass,
      goToNoteDetail
    };
  }
}
</script>

<style scoped lang="less">
.discover-content-container {
  .category-content-container {
    padding: 10px;
    
    .discover-items {
      display: flex;
      flex-wrap: wrap;
      width: 100%;
      max-width: 760px; /* 容器最大宽度，确保两个item和边距正好适合 */
      margin: 0 auto;
      justify-content: space-between;
      
      .discover-item {
        width: calc(50% - 10px);
        height: 660px;
        margin: 10px 0;
        background-color: #fff;
        border-radius: 8px;
        overflow: hidden;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        
        .discover-image {
          position: relative;
          height: 476px;
          overflow: hidden;
          
          img, .video-preview {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
          
          .category-tag {
            position: absolute;
            top: 12px;
            left: 12px;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 14px;
            color: #fff;
            z-index: 2;
          }
          
          .live-tag {
            background-color: #ff2442;
          }
          
          .drama-tag {
            background-color: #ff8f00;
          }
        }
        
        .discover-title {
          width: 100%;
          height: 72px;
          margin: 15px 0 25px 3px;
          font-size: 28px;
          line-height: 1.3;
          font-weight: bold;
          color: #000;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          line-clamp: 2;
          -webkit-box-orient: vertical;
        }
        
        .discover-user {
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin: 0 15px;
          
          .user-info {
            display: flex;
            align-items: center;
            
            .small-avatar {
              width: 34px;
              height: 34px;
              border-radius: 50%;
              margin-right: 8px;
            }
            
            span {
              font-size: 24px;
              color: #666;
              max-width: 130px;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }
          }
          
          .publish-date {
            display: flex;
            align-items: center;
            padding: 5px 10px;
            background-color: rgba(0, 0, 0, 0.03);
            border-radius: 16px;
            
            .calendar-icon {
              width: 20px;
              height: 20px;
              margin-right: 6px;
              color: #666;
            }
            
            .date {
              font-size: 20px;
              color: #666;
              font-weight: 500;
            }
          }
        }
      }
    }
  }
}
</style> 